package com.muyu.cloud.common.saas.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.muyu.cloud.common.saas.contents.SaaSConstant;
import com.muyu.cloud.common.many.datasource.holder.DynamicDataSourceHolder;
import com.muyu.cloud.common.saas.exception.SaaSException;
import com.muyu.cloud.common.many.datasource.role.DynamicDataSource;
import com.muyu.common.core.utils.ServletUtils;
import com.muyu.common.core.utils.SpringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;


/**
 * @Author: DongZeLiang
 * @date: 2024/6/3
 * @Description: SAAS拦截器
 * @Version: 1.0
 */
public class SaaSInterceptor implements AsyncHandlerInterceptor {

    /**
     * 之前
     */
    @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String SaaSKey = ServletUtils.getHeader(request, SaaSConstant.SAAS_KEY);
        if (SaaSKey == null) {
            throw new SaaSException("SaaS非法访问");
        }else {
            DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
            if (!dynamicDataSource.hashKey(SaaSKey)){
                throw new SaaSException("SaaS非法访问");
            }
        }
        DynamicDataSourceHolder.setDynamicDataSourceKey(SaaSKey);
        return true;
    }

    /**
     * 之后
     */
    @Override
    public void afterConcurrentHandlingStarted (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        DynamicDataSourceHolder.removeDynamicDataSourceKey();
    }
}
